package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{

private BrandService brandService = new BrandServiceImpl();

    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用service查询
        List<Brand> brands = brandService.selectAll();
        //将Brand对象转换为JSON数据
        String jsonString = JSON.toJSONString(brands);
        //写入数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    public  void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //解决中文乱码
        request.setCharacterEncoding("utf-8");
        //接收数据
        BufferedReader br = request.getReader();
        String params = br.readLine();
        //将JSON数据转化为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);
        //调用service方法
        brandService.add(brand);
        //添加成功 发送成功的标识
        response.getWriter().write("success");
    }

    public  void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //接收数据 [1,2,3] json字符串
        BufferedReader br = request.getReader();
        String params = br.readLine();
        //将JSON数据转化为数组
        int[] ids = JSON.parseObject(params, int[].class);
        //调用service方法
        brandService.deleteByIds(ids);
        //删除成功 发送成功的标识
        response.getWriter().write("success");
    }
}